package com.gxar.timeline.server.base.common.utils;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 价格单位转化
 *
 * @author linsy
 * @date 2023/09/26
 */
public class PriceUnitParser {

    public static class PriceUnit {
        /**
         * 价格
         */
        private final BigDecimal price;
        /**
         * 单位
         */
        private final String unit;

        public PriceUnit(BigDecimal price, String unit) {
            this.price = price;
            this.unit = unit;
        }

        public BigDecimal getPrice() {
            return price;
        }

        public String getUnit() {
            return unit;
        }

        @Override
        public String toString() {
            return price + " " + unit;
        }
    }

    public static PriceUnit parsePriceUnit(String input) {
        if (input == null || input.isEmpty()) {
            throw new IllegalArgumentException("输入不能为空");
        }

        // 使用正则表达式来匹配价格和单位
        // 假设价格是一个浮点数，单位是一个非空字符串
        String regex = "([0-9.]+)\\s*([^\\d\\s]+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            BigDecimal price = new BigDecimal(matcher.group(1));
            String unit = matcher.group(2).trim();
            return new PriceUnit(price, unit);
        } else {
            throw new IllegalArgumentException("无法解析价格");
        }
    }

    public static void main(String[] args) {
        String input = "3000美元"; // 示例输入字符串
        try {
            PriceUnit priceUnit = parsePriceUnit(input);
            System.out.println("价格：" + priceUnit.getPrice());
            System.out.println("单位：" + priceUnit.getUnit());
        } catch (IllegalArgumentException e) {
            System.err.println("解析失败：" + e.getMessage());
        }
    }
}
